#include <stdlib.h>
#include <stdio.h>

typedef int Freq;
typedef unsigned short int Symbol;

struct HuffTree {
    struct HuffTree *left;
    struct HuffTree *right;
    Freq frequency;
    Symbol nbits;
};

typedef struct HuffTree *HuffTree;

HuffTree NewTree() {
    HuffTree NewTree = malloc(sizeof(struct HuffTree));
    if(NewTree != NULL) {
        NewTree->left = NULL;
        NewTree->right = NULL;
    }
    return NewTree;
}

void DelTree(HuffTree root) {
    if(root != NULL) {
        DelTree(root->left);
        DelTree(root->right);
        free(root);
    }
}

void SetSymbol(HuffTree root, Symbol character) {
    root->nbits = character;
}

void SetFrequency(HuffTree root, Freq frequency) {
	root->frequency = frequency;
}


void SetLeft(HuffTree root, HuffTree lst) {
    if(root->left != NULL) {
        DelTree(root->left);
    }
    root->left = lst;
}

void SetRight(HuffTree root, HuffTree rst) {
    if(root->right != NULL) {
        DelTree(root->right);
    }
    root->right = rst;
}

Symbol GetSymbol(HuffTree root) {
    return root->nbits;
}

Freq GetFrequency(HuffTree root) {
    return root->frequency;
}

HuffTree GetLeft(HuffTree root) {
    return root->left;
}

HuffTree GetRight(HuffTree root) {
    return root->right;
}

int IsLeaf(HuffTree root) {
    return ((root->left == NULL) && (root->right == NULL)) ? 1 : 0;
}

void PrintTree(HuffTree root) {

	if(GetLeft(root) != NULL)
		PrintTree(GetLeft(root));
	printf("%d\n", GetFrequency(root));
	if(GetRight(root) != NULL)
		PrintTree(GetRight(root));
}

